home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4988 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.2 KB  |  48 lines

  1. Path: ix.netcom.com!netnews
  2. From: genescot@ix.netcom.com(Eugene S. Thompson )
  3. Newsgroups: comp.lang.c++
  4. Subject: External access to private class variables
  5. Date: 2 Feb 1996 00:45:29 GMT
  6. Organization: Netcom
  7. Message-ID: <4ermr9$ii7@cloner2.ix.netcom.com>
  8. NNTP-Posting-Host: ix-sea7-16.ix.netcom.com
  9. X-NETCOM-Date: Thu Feb 01  4:45:29 PM PST 1996
  10.  
  11. I was playing around with references and ran across this situation. I'm
  12. sure it's not original, so I was hoping someone could tell me if it is
  13. an intentional implementation of C++ or if it is a bug.
  14.  
  15. class X 
  16. {
  17. private:
  18.     int value;
  19. public:
  20.     X (int n = 0) { value = n; }
  21.     int& GSValue () { return value; }   // return a reference to the 
  22.                                         // private member "value"
  23. };
  24.     .
  25.     .
  26.     .
  27. main ()
  28. {
  29. X   x1 (20);
  30.  
  31.     printf ("%d\n", x1.GSValue ());     // 20
  32.  
  33. int* pntr = &(x1.GSValue ());
  34.  
  35.     printf ("%d\n", *pntr);             // 20
  36.  
  37.     *pntr = 30;
  38.     printf ("%d\n", x1.GSValue ());     // 30 -> We now have external 
  39.                                         // access to a private member.
  40. }
  41.  
  42. I realize that this implementation is contrived, but I'm sure there are
  43. additional ways of gaining such access. So, what's the deal? 
  44.  
  45. Gene
  46.  
  47.  
  48.